package com.example.project10;

import android.util.Log;

import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;

public class NetworkUtils {
    private static final String BASE_URL = "https://reqres.in/api";
    private static final String TAG = "NetworkUtils";
    private static final String API_KEY = "reqres-free-v1"; // reqres.in的免费API密钥

    public static class ApiResponse {
        public boolean success;
        public String data;
        public String errorMessage;

        public ApiResponse(boolean success, String data, String errorMessage) {
            this.success = success;
            this.data = data;
            this.errorMessage = errorMessage;
        }
    }

    /**
     * 执行POST请求
     * @param endpoint API端点
     * @param jsonData 请求数据
     * @return ApiResponse对象
     */
    public static ApiResponse doPostRequest(String endpoint, String jsonData) {
        HttpURLConnection urlConnection = null;
        try {
            URL url = new URL(BASE_URL + endpoint);
            urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.setRequestMethod("POST");
            urlConnection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
            
            // 添加reqres.in所需的API密钥
            urlConnection.setRequestProperty("x-api-key", API_KEY);
            
            urlConnection.setDoOutput(true);
            urlConnection.setDoInput(true);
            urlConnection.setConnectTimeout(10000);
            urlConnection.setReadTimeout(10000);

            // 发送请求数据
            DataOutputStream dos = new DataOutputStream(urlConnection.getOutputStream());
            dos.write(jsonData.getBytes(StandardCharsets.UTF_8));
            dos.flush();
            dos.close();

            // 获取响应
            int responseCode = urlConnection.getResponseCode();
            InputStream inputStream;
            if (responseCode >= 200 && responseCode < 300) {
                inputStream = urlConnection.getInputStream();
            } else {
                inputStream = urlConnection.getErrorStream();
            }

            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
            StringBuilder response = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                response.append(line);
            }
            reader.close();

            if (responseCode >= 200 && responseCode < 300) {
                return new ApiResponse(true, response.toString(), null);
            } else {
                return new ApiResponse(false, null, response.toString());
            }
        } catch (Exception e) {
            Log.e(TAG, "Error during POST request", e);
            return new ApiResponse(false, null, e.getMessage());
        } finally {
            if (urlConnection != null) {
                urlConnection.disconnect();
            }
        }
    }

    /**
     * 执行GET请求
     * @param endpoint API端点
     * @return ApiResponse对象
     */
    public static ApiResponse doGetRequest(String endpoint) {
        HttpURLConnection urlConnection = null;
        try {
            URL url = new URL(BASE_URL + endpoint);
            urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.setRequestMethod("GET");
            urlConnection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
            
            // 添加reqres.in所需的API密钥
            urlConnection.setRequestProperty("x-api-key", API_KEY);
            
            urlConnection.setConnectTimeout(10000);
            urlConnection.setReadTimeout(10000);

            // 获取响应
            int responseCode = urlConnection.getResponseCode();
            InputStream inputStream;
            if (responseCode >= 200 && responseCode < 300) {
                inputStream = urlConnection.getInputStream();
            } else {
                inputStream = urlConnection.getErrorStream();
            }

            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
            StringBuilder response = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                response.append(line);
            }
            reader.close();

            if (responseCode >= 200 && responseCode < 300) {
                return new ApiResponse(true, response.toString(), null);
            } else {
                return new ApiResponse(false, null, response.toString());
            }
        } catch (Exception e) {
            Log.e(TAG, "Error during GET request", e);
            return new ApiResponse(false, null, e.getMessage());
        } finally {
            if (urlConnection != null) {
                urlConnection.disconnect();
            }
        }
    }
}